﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEngine;


namespace RStudio.Command.Editor
{
    /// <summary>
    /// 
    /// </summary>
    internal class CommandWindow : EditorWindow
    {
        private static Dictionary<string, ICommand> _commandList;
        private string _newCommandName = "";
        private string _newCommandDescription = "";
        private CommandPermission _newCommandPermission = CommandPermission.Normal;
        private string _newCommandUsage = "General";
        private string _searchFilter = "";


        /// <summary>
        /// 
        /// </summary>
        private int _currentPage = 0;
        private int _pageSize = 10;


        static readonly GUIStyle styleYes = new GUIStyle();
        static readonly GUIStyle styleNo = new GUIStyle();

        readonly GUILayoutOption[] optionState = new GUILayoutOption[] { GUILayout.ExpandWidth(true), GUILayout.MaxWidth(100) };
        readonly GUILayoutOption[] optionName = new GUILayoutOption[] { GUILayout.ExpandWidth(true), GUILayout.MaxWidth(200) };
        readonly GUILayoutOption[] optionDesc = new GUILayoutOption[] { GUILayout.ExpandWidth(true), GUILayout.MaxWidth(200) };
        readonly GUILayoutOption[] optionUsage = new GUILayoutOption[] { GUILayout.ExpandWidth(true), GUILayout.MaxWidth(200) };
        readonly GUILayoutOption[] optionPerm = new GUILayoutOption[] { GUILayout.ExpandWidth(true), GUILayout.MaxWidth(70) };
        readonly GUILayoutOption[] optionAction = new GUILayoutOption[] { GUILayout.Width(100) };

        readonly GUILayoutOption[] optionTag = new GUILayoutOption[] { GUILayout.Width(120) };
        readonly GUILayoutOption[] optionNormal = new GUILayoutOption[] { GUILayout.Width(60) };


        [MenuItem("RStudio/命令系统/命令生成器")]
        public static void ShowWindow()
        {
            var window = GetWindow<CommandWindow>(false, "命令生成器", true);

            // 设置窗口大小
            window.minSize = new Vector2(1000, 600);
            window.maxSize = new Vector2(1200, 600);
            window.position = Rect.zero;

        }

        public void OnEnable()
        {
            styleYes.normal.textColor = Color.green;
            styleNo.normal.textColor = Color.red;

            RefreshCommandList();
        }
        public void OnGUI()
        {
            GUILayout.BeginVertical();
            {
                this.DrawCommandCreator();
                GUILayout.Space(10);
                this.DrawSearch();

                this.DrawExistingCommands();
            }
            GUILayout.EndVertical();
        }



        private void RefreshCommandList()
        {
            _commandList = new Dictionary<string, ICommand>();

            // 通过反射获取所有命令实例
            var commandTypes = AppDomain.CurrentDomain.GetAssemblies()
                .SelectMany(assembly => assembly.GetTypes())
                .Where(type => typeof(ICommand).IsAssignableFrom(type) &&
                              !type.IsInterface && !type.IsAbstract);

            foreach (var type in commandTypes)
            {
                try
                {
                    ICommand command = Activator.CreateInstance(type) as ICommand;
                    string key = command.Name.ToLower();

                    if (_commandList.ContainsKey(key))
                    {
                        // 重复命令会被标记
                        continue;
                    }

                    _commandList.Add(key, command);
                }
                catch (Exception ex)
                {
                    UnityEngine.Debug.LogWarning($"无法创建命令实例 {type.Name}: {ex.Message}");
                }
            }
        }


        private void DrawSearch()
        {
            EditorGUILayout.BeginHorizontal("Box");
            {
                EditorLayoutUtil.UniButton("搜索:", EditorStyles.toolbarButton, null, GUILayout.Width(100));
                _searchFilter = EditorGUILayout.TextField(_searchFilter);
            }
            EditorGUILayout.EndHorizontal();
        }

        private void DrawExistingCommands()
        {
            EditorGUILayout.BeginVertical("box");
            {
                EditorGUILayout.BeginHorizontal();
                {
                    GUILayout.Label($"现有命令列表 ({_commandList.Count} 个命令)", EditorStyles.boldLabel);
                    EditorLayoutUtil.UniButton("刷新列表", null, () => this.RefreshCommandList(), optionTag);
                }
                EditorGUILayout.EndHorizontal();
            }

            GUILayout.Space(5);

            // 分页相关变量
            const int pageSize = 10;
            int totalCount = _commandList.Count;
            int pageCount = Mathf.Max(1, (totalCount + pageSize - 1) / pageSize);

            // 确保当前页在有效范围内
            _currentPage = Mathf.Clamp(_currentPage, 0, pageCount - 1);


            EditorGUILayout.BeginHorizontal(GUI.skin.box);
            {
                EditorLayoutUtil.UniText(false, "状态", optionState);
                EditorLayoutUtil.UniText(false, "命令", optionName);
                EditorLayoutUtil.UniText(false, "描述", optionDesc);
                EditorLayoutUtil.UniText(false, "示例", optionUsage);
                EditorLayoutUtil.UniText(false, "权限", optionPerm);
                EditorLayoutUtil.UniText(false, "操作", optionAction);
            }
            EditorGUILayout.EndHorizontal();

            if (_commandList.Count == 0)
            {
                EditorGUILayout.HelpBox("未找到任何命令", MessageType.Info);
            }
            else
            {
                var filteredCommands = GetFilteredCommands();
                int filteredCount = filteredCommands.Count;
                int filteredPageCount = Mathf.Max(1, (filteredCount + pageSize - 1) / pageSize);

                // 确保当前页在过滤后的有效范围内
                if (_currentPage >= filteredPageCount)
                {
                    _currentPage = Mathf.Max(0, filteredPageCount - 1);
                }

                if (filteredCount == 0)
                {
                    EditorGUILayout.HelpBox("没有找到匹配的命令", MessageType.Info);
                }
                else
                {
                    // 显示当前页的数据
                    int startIndex = _currentPage * pageSize;
                    int endIndex = Mathf.Min(startIndex + pageSize, filteredCount);

                    for (int i = startIndex; i < endIndex; i++)
                    {
                        DrawCommandItem(filteredCommands[i]);
                    }

                    // 分页控件
                    DrawPaginationControls(filteredCount, pageSize, filteredPageCount);
                }
            }

            EditorGUILayout.EndVertical();
        }

        private void DrawPaginationControls(int totalCount, int pageSize, int pageCount)
        {
            EditorGUILayout.BeginHorizontal();

            // 分页信息
            int startIndex = _currentPage * pageSize + 1;
            int endIndex = Mathf.Min((_currentPage + 1) * pageSize, totalCount);


            GUILayout.Label($"显示 {startIndex} - {endIndex} 条，共 {totalCount} 条记录");


            GUILayout.FlexibleSpace();


 
            EditorGUI.BeginDisabledGroup(_currentPage == 0);
            {
                EditorLayoutUtil.UniButton("第一页", EditorStyles.toolbarButton, () => _currentPage = 0);
            }
            EditorGUI.EndDisabledGroup();

 
            EditorGUI.BeginDisabledGroup(_currentPage == 0);
            {
                EditorLayoutUtil.UniButton("上一页", EditorStyles.toolbarButton, () => _currentPage--, optionNormal);
            }
            EditorGUI.EndDisabledGroup();

 
            EditorGUILayout.LabelField($"第 {_currentPage + 1} 页 / 共 {pageCount} 页", optionTag);

 
            EditorGUI.BeginDisabledGroup(_currentPage >= pageCount - 1);
            {
                EditorLayoutUtil.UniButton("下一页", EditorStyles.toolbarButton, () => _currentPage++, optionNormal);
            }
            EditorGUI.EndDisabledGroup();

 
            EditorGUI.BeginDisabledGroup(_currentPage >= pageCount - 1);
            {
                EditorLayoutUtil.UniButton("最后一页", EditorStyles.toolbarButton, () => _currentPage = pageCount - 1, optionNormal);
            }
            EditorGUI.EndDisabledGroup();

            // 页码跳转
            GUILayout.Label("跳转到:", GUILayout.Width(50));
            string pageInput = GUILayout.TextField((_currentPage + 1).ToString(), GUILayout.Width(30));
            if (int.TryParse(pageInput, out int newPage) && newPage >= 1 && newPage <= pageCount)
            {
                _currentPage = newPage - 1;
            }

            // 每页显示数量选择
            GUILayout.Label("每页显示:", GUILayout.Width(60));
            string sizeInput = GUILayout.TextField(pageSize.ToString(), GUILayout.Width(30));
            if (int.TryParse(sizeInput, out int newSize) && newSize >= 5 && newSize <= 50)
            {
                // 这里可以添加每页显示数量变更的逻辑
            }

            EditorGUILayout.EndHorizontal();
        }

        private List<ICommand> GetFilteredCommands()
        {
            if (string.IsNullOrEmpty(_searchFilter))
            {
                return _commandList.Values
                    .OrderBy(c => c.Name)
                    .ToList();
            }

            return _commandList.Values
                .Where(c => c.Name.ToLower().Contains(_searchFilter.ToLower()) ||
                           c.Description.ToLower().Contains(_searchFilter.ToLower()))
                .OrderBy(c => c.Name)
                .ToList();
        }


        private void DrawCommandItem(ICommand command)
        {
            bool isDuplicate = _commandList.Values.Count(c => c.Name.ToLower() == command.Name.ToLower()) > 1;

            EditorGUILayout.BeginHorizontal(GUI.skin.box);
            {
                EditorGUILayout.LabelField(isDuplicate ? "⚠ 重复" : "✓ 正常", isDuplicate ? styleNo : styleYes, optionState);
                EditorGUILayout.LabelField(command.Name, optionName);
                EditorGUILayout.LabelField(command.Description, optionDesc);
                EditorGUILayout.LabelField(command.Usage, optionUsage);
                EditorGUILayout.LabelField(command.RequiredPermission.ToString(), optionPerm);

                EditorLayoutUtil.UniButton("编辑", null, () => CommandUtil.OpenCommandScript(command), optionAction);
            }
            EditorGUILayout.EndHorizontal();
        }

        private void DrawCommandCreator()
        {
            EditorGUILayout.BeginVertical("box");
            {
                GUILayout.Label("创建新命令", EditorStyles.boldLabel);
                GUILayout.Space(10);

                _newCommandName = EditorGUILayout.TextField("命令名称", _newCommandName);
                _newCommandDescription = EditorGUILayout.TextField("命令描述", _newCommandDescription);
                _newCommandUsage = EditorGUILayout.TextField("命令分类", _newCommandUsage);
                _newCommandPermission = (CommandPermission)EditorGUILayout.EnumPopup("所需权限", _newCommandPermission);



                GUILayout.Space(10);

                EditorGUILayout.BeginHorizontal();
                {
                    if (GUILayout.Button("生成命令脚本", GUILayout.MaxWidth(100)))
                    {
                        GenerateCommandScript();
                    }

                    if (GUILayout.Button("清空", GUILayout.Width(60)))
                    {
                        ClearInputFields();
                    }
                }
                EditorGUILayout.EndHorizontal();


            }
            EditorGUILayout.EndVertical();
        }

        private void GenerateCommandScript()
        {
            string className = "Command" + _newCommandName;
            string scriptContent = $@"using UnityEngine;

namespace RStudio.Command
{{
    public class {className} : ICommand
    {{
        public string Name => ""{_newCommandName}"";
        public string Description => ""{_newCommandDescription}"";
        public CommandPermission RequiredPermission => CommandPermission.{_newCommandPermission};
        public string Category => ""{_newCommandUsage}"";
        public string Usage => ""{_newCommandName} [参数]"";
        
        public string[] ParamArray {{ get; set; }} = System.Array.Empty<string>();


        public bool CanExecute(string[] args)
        {{
            return true;
        }}

        public bool Execute(string[] args)
        {{
            if (!CanExecute(args)) return false;
            
            // TODO: 实现命令逻辑
            Debug.Log($""执行命令: {{Name}} 参数: {{string.Join("", "", args)}}"");
            
            return true;
        }}
    }}
}}";

            // 默认保存路径
            string defaultPath = Application.dataPath + "/Scripts/Commands";
            if (!Directory.Exists(defaultPath))
            {
                Directory.CreateDirectory(defaultPath);
            }

            string path = EditorUtility.SaveFilePanel("保存命令脚本",
                defaultPath,
                className + ".cs",
                "cs");

            if (!string.IsNullOrEmpty(path))
            {
                File.WriteAllText(path, scriptContent);
                AssetDatabase.Refresh();

                EditorUtility.DisplayDialog("成功", $"命令脚本已生成: {Path.GetFileName(path)}", "确定");
                ClearInputFields();
                RefreshCommandList();
            }
        }

        private void ClearInputFields()
        {
            _newCommandName = "";
            _newCommandDescription = "";
            //_newCommandUsage = "General";
            //_newCommandPermission = CommandPermission.Normal;
        }
    }
}